#!/usr/bin/env bash

declare -r SRC_DIR="/app/data/k8s/registry"
declare -r DEST_DIR="/app/ssl/registry"

rm -Rfv ${DEST_DIR}
mkdir -pv ${DEST_DIR}
pushd ${DEST_DIR}

cp -fv ${SRC_DIR}/*.* .
chmod -x *.*

openssl genrsa -out ca.key 4096

openssl req -new -sha256 -out ca.csr -key ca.key -config ca.conf

openssl x509 -req -days 3650 -in ca.csr -signkey ca.key -out ca.crt

openssl genrsa -out registry.key 2048

openssl req -new -sha256 -out registry.csr -key registry.key -config registry.conf

openssl x509 -req -days 3650 \
  -CA ca.crt -CAkey ca.key -CAcreateserial \
  -in registry.csr -out registry.pem \
  -extensions req_ext \
  -extfile registry.conf

popd

mkdir -pv "/etc/docker/certs.d/docker-hub:5000"
cp -fv ${DEST_DIR}/registry.pem "/etc/docker/certs.d/docker-hub:5000/ca.crt"

pushd ~
cp -fv /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem ~/tls-ca-bundle.pem.ori
cp -fv ~/tls-ca-bundle.pem.ori ~/tls-ca-bundle.pem
chmod +w ~/tls-ca-bundle.pem
cat ${DEST_DIR}/ca.crt >> ~/tls-ca-bundle.pem
chmod -w ~/tls-ca-bundle.pem
cp -fv ~/tls-ca-bundle.pem /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem
popd
